package com.novel.resource.oss.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.novel.common.resource.IResourceService;
import com.novel.resource.oss.config.OssConfig;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * 资源存储服务实现类
 *
 * @author novel
 * @date 2019/6/4
 */
@AllArgsConstructor
public class OssResourceServiceImpl implements IResourceService {
    /**
     * oss 操作客户端
     */
    private OSS ossClient;
    /**
     * oss 配置信息
     */
    private OssConfig ossConfig;
    /**
     * 文件访问连接最大超时时间
     */
    private int fileCacheMaxTime;

    @Override
    public String getFileUrl(String sourceUrl) throws IOException {
        return ossClient.generatePresignedUrl(ossConfig.getBucketName(), sourceUrl, new Date(System.currentTimeMillis() + (1000 * 60 * fileCacheMaxTime)), com.aliyun.oss.HttpMethod.GET).toString();
    }

    @Override
    public boolean upLoadFile(String sourceUrl, String destPath) throws IOException {
        ossClient.putObject(ossConfig.getBucketName(), destPath, new File(sourceUrl));
        return true;
    }

    @Override
    public boolean upLoadFile(InputStream source, String destPath) throws IOException {
        ossClient.putObject(ossConfig.getBucketName(), destPath, source);
        return true;
    }

    @Override
    public void download(String filePath, String localPath) throws IOException {
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(ossConfig.getBucketName(), filePath), new File(localPath));
    }

    @Override
    public boolean delete(String filePath) throws IOException {
        // 删除文件。
        ossClient.deleteObject(ossConfig.getBucketName(), filePath);
        return true;
    }

    @Override
    public byte[] readBytes(String filePath) throws IOException {
        try (InputStream inputStream = ossClient.getObject(ossConfig.getBucketName(), filePath).getObjectContent()) {
            return IOUtils.toByteArray(inputStream);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }
}
